#include <sys/res.h>
#include <os/driver.h>
#include <driver/view/hal.h>
#include <driver/view/keyboard.h>
#include <lib/string.h>
#include <lib/stdint.h>
#include <lib/stdio.h>
#include <sys/ioctl.h>

#ifndef DEVICE_NAME
#define DEVICE_NAME "tty7"
#endif

//#define DEBUG_KEYBOARD_HAL

int ViewKeyboardOpen(view_keyboard_t *keyboard)
{
    keyboard->handle = DeviceOpen(DEVICE_NAME, 0);
    if (keyboard->handle < 0)
        return -1;
    keyboard->ledstatus = 0;
    int flags = TTYFLAG_NOWAIT;
    DeviceDevCtl(keyboard->handle, TTYIO_SETFLAGS, &flags);
    flags = TTYIO_RAW;
    DeviceDevCtl(keyboard->handle, TTYIO_SELECT, &flags);
    return 0;
}

int ViewKeyboardClose(view_keyboard_t *keyboard)
{
    return DeviceClose(keyboard->handle);
}

int ViewKeyboardRead(view_keyboard_t *keyboard)
{
    uint8_t ttybuff[2];
    int ret = 0;
    ret = DeviceRead(keyboard->handle, ttybuff, 2, 0);
    if (ret < 0)
        return -1;
    #ifdef DEBUG_KEYBOARD_HAL
    KPrint("[view] keyboard read ok,data0 %d data1 %d\n",ttybuff[0],ttybuff[1]);
    #endif 

    if (!ttybuff[1])
        return keyboard->keydown(ttybuff[0]);
    else
        return keyboard->keyup(ttybuff[0]);
    return -1;
    
}
